import datetime
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import User
from taggit.managers import TaggableManager

# Create your models here.

class Poll(models.Model):
  question = models.CharField(max_length=200)
  pub_date = models.DateTimeField('date published')
  deadline = models.DateTimeField(default=(timezone.now() + datetime.timedelta(days=10)))
  tags = TaggableManager()

  def __unicode__(self):
    return self.question

  def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

  def get_total_votes(self):
    return sum([choice.votes for choice in self.choice_set.all()])

  def get_total_bets(self):
    total_bets = 0
    for choice in self.choice_set.all():
      total_bets += choice.get_bets()
    return total_bets

  def is_active(self):
    return (self.deadline > timezone.now())

class Choice(models.Model):
  poll = models.ForeignKey(Poll)
  choice_text = models.CharField(max_length=200)
  votes = models.IntegerField()
  def __unicode__(self):
    return self.choice_text
  def get_bets(self):
    return sum([vote.amount for vote in self.vote_set.all()])

class Vote(models.Model):
  amount = models.IntegerField()
  choice = models.ForeignKey(Choice)
  user = models.ForeignKey(User)
  def __unicode__(self):
    return "User:%s  Choice:%s  Amount:$%s" % (self.user.username, self.choice.choice_text, self.amount)
